#include "head.h"

// 功能：建立TCP连接
int establishConnect(char *ip, char *port){
    
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in saddr;
    saddr.sin_addr.s_addr = inet_addr(ip);
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(atoi(port));

    int flag = 1;
    int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    ERROR_CHECK(ret, -1, "opt");

    ret = bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
    ERROR_CHECK(ret, -1, "bind");
    
    listen(sockfd, 10);

    return sockfd;
}

// 功能：添加监听
int epollAdd(int efd, int monitorfd){
    
    struct epoll_event event;
    bzero(&event, sizeof(event));
    event.events = EPOLLIN;
    event.data.fd = monitorfd;

    epoll_ctl(efd, EPOLL_CTL_ADD, monitorfd, &event);

    return 0;

}

int epollDel(int efd, int delfd){
    epoll_ctl(efd, EPOLL_CTL_DEL, delfd, NULL);
    return 0;
}

int TLVResponse(int sockfd, const char *buf, int type){
    send(sockfd, &type, sizeof(int), MSG_NOSIGNAL);
    int len = strlen(buf);
    send(sockfd, &len, sizeof(int), MSG_NOSIGNAL);
    send(sockfd, buf, len, MSG_NOSIGNAL);
    return 0;
}

int recvOrderTrain(int sockfd, train_t *train){
    int ret = recv(sockfd, &train->type, sizeof(int), MSG_WAITALL);
    if(ret <= 0){
        return -1;
    }
    recv(sockfd, &train->len, sizeof(int), MSG_WAITALL);
    if(train->len){
        recv(sockfd, train->buf, train->len, MSG_WAITALL);
    }
    return 0;
}

                                   
// 功能：接收请求                  
int recvRequest(int sockfd, train_t *train){
    bzero(train, sizeof(train_t));

    int ret = recv(sockfd, &train->type, sizeof(int), MSG_WAITALL);
    if(train->type == LS || train->type == PWD){
        return 0;
    }
    ret = recv(sockfd, &train->len, sizeof(int), MSG_WAITALL);
    // 传送的是文件大小
    if(train->type != FILE_LEN){
        ret = recv(sockfd, train->buf, train->len, MSG_WAITALL);
    }

    if(ret <= 0){
        return -1;
    }
    return 0;
}

